#include "database.h"

db_t *createDB()
{
    db_t *db = (db_t *) malloc(sizeof(db_t));
    if (db == NULL) {
        fprintf(stderr, "create db error\n");
        exit(EXIT_FAILURE);
    }

#ifdef _WIN32
    _mkdir(DEFAULT_DIR);   /* Windows */
#else
    mkdir(DEFAULT_DIR, 0777);  /* Unix/Linux/macOS */
#endif
    snprintf(db->dbname, MAX_DBNAME_LEN, "%s/dbfile-%ld", DEFAULT_DIR, time(NULL) % 1000);

    db->user = createTable(USER);
    db->book = createTable(BOOK);
    db->borrow = createTable(BORROW);

    return db;
}

void destroyDB(db_t *db)
{
    destroyTable(db->user);
    destroyTable(db->book);
    destroyTable(db->borrow);

    free(db);
    db = NULL;
}

/*
 * flush order should be same to load order
 * user - book - borrow
 */

int flushToDisk(db_t *db, const char *filename)
{
    FILE *file = fopen(filename, "wb");
    if (file == NULL) {
        printf("OPEN ERROR: .flush\n");
        return -1;
    }

    fwrite(MAGIC_NUMBER, sizeof(char), strlen(MAGIC_NUMBER), file);

    flushPages(db->user, file);
    flushPages(db->book, file);
    flushPages(db->borrow, file);

    fclose(file);

    return 0;
}

int loadFromDisk(db_t *db, const char *filename)
{
    FILE *file = fopen(filename, "rb");
    if (file == NULL) {
        printf("OPEN ERROR: .load\n");
        return -1;
    }
    char magic[100];
    fread(magic, sizeof(char), strlen(MAGIC_NUMBER), file);
    if (strncmp(magic, MAGIC_NUMBER, strlen(MAGIC_NUMBER)) != 0) {
        fprintf(stderr, "NOT A DATABASE FILE: '%s'\n", filename);
        fclose(file);
        return -1;
    }

    loadPages(db->user, file);
    loadPages(db->book, file);
    loadPages(db->borrow, file);

    fclose(file);

    return 0;
}